package com.qf.common.interceptor;


import com.qf.common.annotation.NoLoginCheck;
import com.qf.common.utils.JwtUtils;
import com.qf.common.utils.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod){
            // spring中,将控制层的方法封装为HandlerMethod对象
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            // 判断方法上是否存在指定的注解
            boolean ret = method.isAnnotationPresent(NoLoginCheck.class);
            if (ret){
                //如果使用了@NoLoginCheck,直接放行
                return true;
            }else {
                String token = request.getHeader("Token");
                if (token==null||token.isEmpty()){
                    throw new RuntimeException("请先登录");
                }
                try {
                    Claims claims = JwtUtils.parseJWT(token);
                    Object uid = claims.get("uid");
                    // 将用户信息存入ThreadLocal
                    UserUtils.setUid(Integer.valueOf(uid.toString()));
                } catch (Exception e) {
                    throw new RuntimeException("请重新登录");
                }
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除数据
        UserUtils.removeId();
    }
}
